package server;

import model.*;

public class Game {
	private Client one, two;
	private ServerController controller;
	private ServerButton[] buttons;
	private int moves;
	private boolean gameOver;

	public Game(Client one, Client two, ServerController controller) {
		this.one = one;
		this.two = two;
		this.controller = controller;
		buttons = new ServerButton[9];
		moves = 0;
		gameOver = false;
	}

	public boolean containsUser(Client user) {
		return one.equals(user) || two.equals(user);
	}

	public void sendMessage(Message message) {
		controller.sendMessageTo(message, one);
		controller.sendMessageTo(message, two);
	}

	public void stop(Client user) {
		if (one.equals(user))
			controller.endGameOf(two);
		else
			controller.endGameOf(one);
	}

	public void gameOverCheck() {
		checkOne(0, 1, 2);
		checkOne(3, 4, 5);
		checkOne(6, 7, 8);

		checkOne(0, 3, 6);
		checkOne(1, 4, 7);
		checkOne(2, 5, 8);

		checkOne(0, 4, 8);

		checkOne(2, 4, 6);

		checkDraw();
	}

	private void checkDraw() {
		if (moves == 9 && !gameOver)
			done(null);
	}

	private void checkOne(int pos1, int pos2, int pos3) {
		if (buttons[pos1] != null && buttons[pos2] != null
				&& buttons[pos3] != null && !gameOver
				&& buttons[pos1].getSymbol().equals(buttons[pos2].getSymbol())
				&& buttons[pos1].getSymbol().equals(buttons[pos3].getSymbol()))
			done(buttons[pos1].getSymbol());
	}

	private void done(String winner) {
		gameOver = true;
		if (winner == null)
			controller.draw(one, two);
		else if (winner.equals("X"))
			controller.winner(one, two);
		else
			controller.winner(two, one);
	}

	public void sendButton(ServerButton button) {
		moves++;
		buttons[button.getNo()] = button;
		controller.sendButton(button, one);
		controller.sendButton(button, two);
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		gameOverCheck();
	}

	public void restart() {
		moves = 0;
		gameOver = false;
		for (int i = 0; i < 9; i++)
			buttons[i] = null;
		controller.resetButtons(one, true);
		controller.resetButtons(two, false);
	}
}
